<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <div class="flex items-center gap-3">
            <div class="flex items-center gap-2">
              <div class="w-10 h-10 rounded-lg overflow-hidden">
                <img src="../../../头像.jpg" alt="头像" class="w-full h-full object-cover">
              </div>
              <span class="text-xl font-semibold text-gray-900">校园快递代拿</span>
            </div>
            <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded">下单者</span>
          </div>
          <HeaderActions />
        </div>
      </div>
    </header>

    <!-- 标签页导航 -->
    <nav class="bg-white border-b border-gray-200">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex gap-8">
          <button class="py-4 text-gray-600 hover:text-gray-900 border-b-2 border-transparent hover:border-gray-300" @click="$router.push('/order/publish')">发布订单</button>
          <button class="py-4 text-blue-600 border-b-2 border-blue-600 font-medium">我的订单</button>
          <button class="py-4 text-gray-600 hover:text-gray-900 border-b-2 border-transparent hover:border-gray-300" @click="$router.push('/order/profile')">我的主页</button>
        </div>
      </div>
    </nav>

    <!-- 主要内容区域（带筛选和搜索） -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <h1 class="text-2xl font-bold text-gray-900 mb-6">我的订单</h1>
      <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="flex flex-wrap items-center gap-6">
          <div class="flex items-center gap-3">
            <span class="text-sm text-gray-600">订单状态:</span>
            <div class="flex gap-2">
              <button @click="status='all'" :class="btnCls('all')">全部</button>
              <button @click="status='pending'" :class="btnCls('pending')">待接单</button>
              <button @click="status='ongoing'" :class="btnCls('ongoing')">配送中</button>
              <button @click="status='picked'" :class="btnCls('picked')">已取件</button>
              <button @click="status='delivered'" :class="btnCls('delivered')">已送达</button>
              <button @click="status='completed'" :class="btnCls('completed')">已完成</button>
              <button @click="status='cancelled'" :class="btnCls('cancelled')">已取消</button>
            </div>
          </div>
          <div class="flex-1 min-w-[200px]">
            <div class="relative">
              <input v-model="keyword" type="text" placeholder="搜索订单号、物品信息" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
              <svg class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="space-y-4">
        <div v-for="order in pagedOrders" :key="order.id" class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center gap-3">
              <span class="text-sm text-gray-600">订单编号: {{ order.id }}</span>
              <span class="px-2 py-1 text-xs rounded" :class="badgeCls(order.status)">{{ statusLabel(order.status) }}</span>
            </div>
            <span class="text-sm text-gray-500">{{ order.time }}</span>
          </div>
          <div class="mb-4">
            <h3 class="text-lg font-semibold text-gray-900 mb-1">{{ order.title }}</h3>
            <p class="text-sm text-gray-600">{{ order.desc }}</p>
          </div>
          <div class="flex items-center justify-between pt-4 border-t border-gray-200">
            <div class="text-sm text-gray-600">订单金额</div>
            <div class="flex items-center gap-4">
              <span class="text-xl font-bold text-gray-900">¥{{ order.amount }}</span>
              <div class="flex gap-2">
                <button v-if="canContact(order)" class="px-4 py-2 text-sm text-blue-600 border border-blue-600 rounded hover:bg-blue-50" @click="contactCourier(order.id)">联系接手</button>
                <button v-if="order.status === 'delivered'" class="px-4 py-2 text-sm bg-green-600 text-white rounded hover:bg-green-700" @click="$router.push('/payment?orderId=' + order.id)">支付订单</button>
                <button class="px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded" @click="$router.push('/order/detail/' + order.id)">查看详情</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="flex items-center justify-center gap-2 mt-8">
        <!-- 上一页 -->
        <button
          class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-white"
          :disabled="currentPage === 1"
          @click="currentPage > 1 && (currentPage -= 1)"
        >
          <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
          </svg>
        </button>

        <!-- 中间页码：1 ~ totalPages -->
        <button
          v-for="p in totalPages"
          :key="p"
          class="w-8 h-8 flex items-center justify-center rounded border"
          :class="p === currentPage ? 'bg-blue-600 text-white border-blue-600' : 'border-gray-300 text-gray-600 hover:bg-gray-100'"
          @click="currentPage = p"
        >
          {{ p }}
        </button>

        <!-- 下一页 -->
        <button
          class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-white"
          :disabled="currentPage === totalPages"
          @click="currentPage < totalPages && (currentPage += 1)"
        >
          <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
          </svg>
        </button>
      </div>
    </main>
  </div>
</template>

<script>
import axios from 'axios'
import HeaderActions from '../components/HeaderActions.vue'
export default {
  name: 'OrderMy',
  components: { HeaderActions },
  data() {
    return {
      status: 'all',
      keyword: '',
      orders: [],
      unread: 0,
      unreadTimer: null,
      currentPage: 1,
      pageSize: 10
    }
  },
  async mounted() {
    const userId = Number(localStorage.getItem('userId'))
    if (!userId) { this.$router.push('/login'); return }
    await this.fetchMyOrders()
    this.pollUnread()
  },
  computed: {
    filteredOrders() {
      const kw = this.keyword.trim().toLowerCase()
      return this.orders.filter(o => {
        const statusOk = this.status === 'all' ? true : o.status === this.status
        const kwOk = kw === '' ? true : (o.id + ' ' + o.title + ' ' + o.desc).toLowerCase().includes(kw)
        return statusOk && kwOk
      })
    },
    // 总页数（基于过滤后的结果动态计算）
    totalPages() {
      const total = this.filteredOrders.length
      if (total === 0) return 1
      return Math.ceil(total / this.pageSize)
    },
    // 当前页要展示的订单列表
    pagedOrders() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredOrders.slice(start, end)
    }
  },
  methods: {
    async fetchMyOrders() {
      const userId = Number(localStorage.getItem('userId'))
      if (!userId) { this.$router.push('/login'); return }
      try {
        const { data } = await axios.get(`/api/orders/user/${userId}`)
        if (data && data.success !== false) {
          const list = data.data || []
          // 状态映射（与后端保持一致）：1=待接单, 2=配送中, 3=已取件, 4=已送达, 5=已完成, 6=已取消
          this.orders = list.map(r => {
            const s = Number(r.status)
            let status = 'pending'
            if (s === 1) status = 'pending'
            else if (s === 2) status = 'ongoing'
            else if (s === 3) status = 'picked'      // 已取件
            else if (s === 4) status = 'delivered'   // 已送达
            else if (s === 5) status = 'completed'
            else if (s === 6) status = 'cancelled'
            
            return {
              id: r.id,
              title: r.title || `取件码：${r.pickup_code || '—'}`,
              desc: r.desc || r.note || '',
              amount: Number((r.final_fee ?? r.suggested_fee ?? r.amount ?? r.fee ?? 0)).toFixed(2),
              status: status,
              time: (r.time || r.created_at || '').replace('T',' ').slice(0,19),
              courier_user_id: r.courier_user_id || r.courier_user || null
            }
          })
        }
      } catch (e) {
        console.error('获取我的订单失败', e)
      }
    },
    logout() {
      localStorage.removeItem('userToken')
      this.$router.push('/login')
    },
    canContact(o){
      // 只有已被代拿员接单，且订单仍在进行中（配送中/已取件/已送达）时允许联系
      return o && o.courier_user_id && (o.status === 'ongoing' || o.status === 'picked' || o.status === 'delivered')
    },
    async contactCourier(orderId){
      const me = Number(localStorage.getItem('userId'))
      if (!me) { this.$router.push('/login'); return }
      try {
        const { data } = await axios.get(`/api/orders/${orderId}`)
        const d = (data && data.data) || {}
        // courier_user 为后端返回的接手人 users.id，优先使用
        const courierId = Number(d.courier_user || d.courier_user_id || 0)
        if (!courierId) { alert('暂无接手人，无法发起对话'); return }
        const { data: created } = await axios.post('/api/messages/conversations', { participants: [me, courierId], order_id: Number(orderId), type: 1 })
        const cid = created && created.data && created.data.id
        this.$router.push({ path: '/messages', query: { cid } })
      } catch(e){
        console.error('联系接手失败', e)
        alert('联系接手失败，请稍后再试')
      }
    },
    statusLabel(s) {
      const statusMap = {
        'pending': '待接单',
        'ongoing': '配送中',
        'picked': '已取件',
        'delivered': '已送达',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[s] || s
    },
    btnCls(name) {
      return this.status === name
        ? 'px-3 py-1 text-sm bg-blue-600 text-white rounded'
        : 'px-3 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded'
    },
    badgeCls(s) {
      const classMap = {
        'pending': 'bg-gray-100 text-gray-600',
        'ongoing': 'bg-yellow-100 text-yellow-700',
        'picked': 'bg-amber-100 text-amber-700',
        'delivered': 'bg-blue-100 text-blue-700',
        'completed': 'bg-green-100 text-green-700',
        'cancelled': 'bg-red-100 text-red-700'
      }
      return classMap[s] || 'bg-gray-100 text-gray-600'
    },
    async pollUnread(){
      const me = Number(localStorage.getItem('userId'))
      if (!me) return
      const fetchOnce = async () => {
        try {
          const { data } = await axios.get('/api/messages/unread-count', { params: { userId: me } })
          this.unread = (data && data.data && data.data.unread) || 0
        } catch {}
      }
      await fetchOnce()
      this.unreadTimer = setInterval(fetchOnce, 10000)
    }
  }
}
</script>


